package com.sanploy.manage.service.impl;

import com.sanploy.common.conf.PubliceVariable;
import com.sanploy.common.conf.SysConfig;
import com.sanploy.common.domain.dto.ReduceStockDto;
import com.sanploy.common.enums.OrderStatus;
import com.sanploy.common.util.CommonUtil;
import com.sanploy.common.vo.BaseException;
import com.sanploy.manage.service.GoodsService;
import com.sanploy.manage.service.OrderService;
import com.sanploy.manage.service.OrderTimerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by zhu yingzhi on 2017/10/11.
 * @author yingzhi zhu
 * 订单定时任务逻辑处理接口实现
 */
@Service
public class OrderTimerServiceImpl implements OrderTimerService {
    @Autowired
    private OrderService orderService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    private SysConfig sysConfig = new SysConfig();


    //暂时停用 订单取消队列 订单确认队列
    public Set<String> orderCancerQueue = new HashSet<>();
    public Set<String> orderConfirmQueue = new HashSet<>();


    @Override
    public void startTimer() {
        OrderCancerListen();
        orderConfirmListen();
    }

    //用户待支付订单自动取消
    @Override
    public void userOrderCancelDelete(List<String> orderList) {
        orderList.forEach(this::userOrderCancelDelete);
    }

    //用户待支付订单自动取消
    @Override
    public void userOrderCancelDelete(String orderId){
        //改变状态
        if (orderService.autoChangeOrdersStatus(orderId,OrderStatus.Cancelled,OrderStatus.NotPay,
                CommonUtil.getBeforeTime(sysConfig.getCancerTime()))>=PubliceVariable.MinEffectRow){
            //如果redis中存在 该订单的下单库存信息 则恢复原有库存 并删除原有数据
            Optional.ofNullable(redisTemplate.opsForValue().get(PubliceVariable.RedisOrderStock+orderId)).ifPresent(orderStock->{
                goodsService.restoreGoodsStock((ReduceStockDto)orderStock);
                redisTemplate.delete(PubliceVariable.RedisOrderStock+orderId);
            });
        }
    }

    //用户待支付订单添加进取消队列
    @Override
    public void userOrderCancelteAdd(String order_id){
//        orderCancerQueue.add(order_id);
    }

    @Override
    public void userOrderAutoCancel(Long user_id) {
        userOrderCancelDelete(orderService.findUserOrdersByStatus(user_id,OrderStatus.NotPay));
    }

    @Override
    public void userOrderAutoConfirm(Long user_id) {
        userOrderConfirmDelete(orderService.findUserOrdersByStatus(user_id,OrderStatus.ReceiveGoods));
    }

    @Override
    public void userOrderConfirmDelete(String order_id) {

       orderService.autoChangeOrdersStatus(order_id,OrderStatus.Complete,OrderStatus.ReceiveGoods,
                CommonUtil.getBeforeTime(sysConfig.getConfirmTime()));
    }

    @Override
    public void userOrderConfirmDelete(List<String> orderList) {
        orderList.forEach(item->{
            if (orderService.autoChangeOrdersStatus(item, OrderStatus.Complete,OrderStatus.ReceiveGoods,
                    CommonUtil.getBeforeTime(sysConfig.getConfirmTime()))>= PubliceVariable.MinEffectRow){ //当更新成功后就删除它

            }
        });
    }


    /**
     * 订单自动取消监听器
     */
    private void OrderCancerListen(){
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                List<String> list =orderService.findOrdersByStatus(OrderStatus.NotPay);
                    //取消每条订单
                    list.forEach(value->{
                        userOrderCancelDelete(value);
                    });

                System.out.println(CommonUtil.getTimeNormal()+"自动取消订单任务执行");
            }
        },0,sysConfig.getCancerTime());
    }

    /**
     * 订单自动确认监听器
     */
    private void orderConfirmListen(){
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                List<String> list = orderService.findOrdersByStatus(OrderStatus.ReceiveGoods);
                try {
                    orderService.autoChangeOrdersStatus(list,OrderStatus.Complete,OrderStatus.ReceiveGoods,
                            CommonUtil.getBeforeTime(sysConfig.getConfirmTime()));
                } catch (BaseException e) {
                    e.printStackTrace();
                }

                System.out.println(CommonUtil.getTimeNormal()+"自动确认订单任务执行");

            }
        },0,sysConfig.getConfirmTime());
    }

}
